package main

import "fmt"

func main() {
	s1 := []int{1, 2, 3, 4}
	fmt.Printf("s1: %v len: %d, cap: %d \n", s1, len(s1), cap(s1))

	// 初始化三个元素，容量为 4 的切片
	s2 := make([]int, 3, 4)
	fmt.Printf("s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s2 = append(s2, 5)
	fmt.Printf("append 5, s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s2 = append(s2, 6)
	fmt.Printf("append 6, s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	println(s2[3])

	// panic，不能超过长度 len
	//println(s2[7])

	// make([]int, 4, 4)
	s3 := make([]int, 4)
	fmt.Printf("s3: %v len: %d, cap: %d \n", s3, len(s3), cap(s3))

	subSlice()

	ShareSlice()
}

func subSlice() {
	s1 := []int{2, 4, 6, 8, 10}
	s2 := s1[1:3]
	fmt.Printf("subslice s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s3 := s1[2:]
	fmt.Printf("subslice s3: %v len: %d, cap: %d \n", s3, len(s3), cap(s3))
	s4 := s1[:4]
	fmt.Printf("subslice s4: %v len: %d, cap: %d \n", s4, len(s4), cap(s4))

	a1 := [3]int{1, 2, 3}
	as1 := a1[:2]
	fmt.Printf("subslice as1: %v len: %d, cap: %d \n", as1, len(as1), cap(as1))
}

func ShareSlice() {
	s1 := []int{1, 2, 3, 4}
	s2 := s1[2:]
	fmt.Printf("share slice s1: %v len: %d, cap: %d \n", s1, len(s1), cap(s1))
	fmt.Printf("share slice s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s2[0] = 99

	fmt.Printf("s2[0]=99 share slice s1: %v len: %d, cap: %d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2[0]=99 share slice s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s2 = append(s2, 199)
	fmt.Printf("append s2 share slice s1: %v len: %d, cap: %d \n", s1, len(s1), cap(s1))
	fmt.Printf("append s2 share slice s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))

	s2[0] = 1999
	fmt.Printf("s2[0] = 1999 share slice s1: %v len: %d, cap: %d \n", s1, len(s1), cap(s1))
	fmt.Printf("s2[0] = 1999 share slice s2: %v len: %d, cap: %d \n", s2, len(s2), cap(s2))
}
